#Author：雨霁夜茶

import requests
import json
import re
import time
import threading


data_value=0
data_dict={}
keys=set()
lock = threading.RLock()

def getdata():
    return data_dict

def load_data():
    while True:
        try:
            res = requests.get("https://www.binance.com/exchange/public/product")
            lock.acquire()

            text = json.loads(res.text)

            count = len(text['data'])
            btc_price=0


            for i in range(count):
                content = text['data'][i]
                data_value = float(content['close'])
                if content['quoteAsset']=='USDT':
                    key = content['baseAsset'].lower()
                    keys.add(key)
                    if key == 'btc':
                        data_dict[key] = {'usdt': data_value, 'btc': 1, 'precent': 0}
                        btc_price = data_value
                        break

            for i in range(count):
                content = text['data'][i]
                data_value = float(content['close'])
                if content['quoteAsset'] == 'USDT':
                    key = content['baseAsset'].lower()
                    keys.add(key)
                    data_dict[key]={'key':key,'usdt':data_value,'btc':0,'precent':0}

            for i in range(count):
                content = text['data'][i]
                data_value = float(content['close'])
                if content['quoteAsset'] == 'BTC':
                    key = content['baseAsset'].lower()
                    keys.add(key)
                    if data_dict.get(key) != None:
                        data_dict.get(key)['btc'] = data_value
                    else:
                        data_dict[key] = {'key': key, 'usdt': data_value * btc_price, 'btc': data_value,
                                                  'precent': 0}
            data_dict['btc']['btc']=1
            lock.release()
            print('下载成功：Binance')
            return data_dict, keys
        except requests.exceptions.RequestException:
            print('RequestException Binance')
            return data_dict, keys
        except requests.exceptions.ConnectionError:
            print('ConnectionError Binance')
            return data_dict, keys
        except :
            print('Error Binance')
            return data_dict, keys



def loadingdata():
    t1 = threading.Thread(target=load_data)
    t1.start()

if __name__ == "__main__":
    loadingdata()
    for k,v in data_dict.items():
        print(k,':',v)